package dao.impl;

import bean.Goods;
import bean.CartItem;
import dao.BaseDao;
import dao.BookDao;
import utils.JdbcUtils;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

public class BookDaoImpl extends BaseDao<Goods> implements BookDao {
    String a=new String();

    @Override
    public int addBook(Goods goods) {
        String sql = "insert into t_goods(`name`,`price`,`sales`,`stock`,`img_path`)" +
                "values(?,?,?,?,?,?)";
        return update(sql, goods.getName(), goods.getPrice(), goods.getSales(), goods.getStock(), goods.getImgPath());
    }

    @Override
    public int deleteBookById(Integer id) {
        String sql = "delete from t_goods where `id` = ?";
        return update(sql,id);
    }

    @Override
    public Goods queryById(Integer id) {
        String sql = "select `id`,`name`,`price`,`sales`,`stock`,`img_path` as imgPath from t_goods where `id` = ?";
        return queryForOne(sql,id);
    }

    @Override
    public List<Goods> queryAllBook() {
        String sql = "select `id`,`name`,`price`,`sales`,`stock`,`img_path` as imgPath from t_goods";
        return query(sql);
    }

    @Override
    public List<Goods> pagingQuery(int begin, int pageSize,String classifyName) {
        StringBuffer str1 = new StringBuffer("select `id`,`name`,`price`,`sales`,`stock`,`img_path` as imgPath from ");
        StringBuffer str2 = str1.append(classifyName);
        StringBuffer str3 = str2.append(" limit ?,?");
        String sql = str3.toString();

        return query(sql,begin,pageSize);
    }

    @Override
    public int updateBook(Goods goods) {
        String sql = "update t_goods set `name` = ?,`price` = ?,`sales` = ?,`stock` = ?,`img_path` = ? where `id` = ?";
        return update(sql, goods.getName(), goods.getPrice(), goods.getSales(), goods.getStock(), goods.getImgPath(),
                goods.getId());
    }

    @Override
    public int getTotal(String classifyName) {
        StringBuffer str1=new StringBuffer("select count(*) from ");
        StringBuffer str2 = str1.append(classifyName);
        String sql =str2.toString();
        Number number = (Number)queryForValue(sql);
        return number.intValue();
    }

    /**
     * 结算购物车后，更新库存和销量
     */
    @Override
    public int[] syncStockAndSales(List<CartItem> cartItems) {
        String sql = "update t_goods set `sales` = `sales` + ? ,`stock` = `stock` - ? where id = ?";

        List<Integer> stockOutBooks = new ArrayList<>();
        Connection conn = null;
        Boolean isException = false;

        for (int i = 0; i < cartItems.size(); i++) {
            //更新库存
            try {
                update(sql, cartItems.get(i).getCount(), cartItems.get(i).getCount(), cartItems.get(i).getBookId());
            } catch (Exception e) {
                   isException = true;
                //记录库存不足的图书id
                stockOutBooks.add(cartItems.get(i).getBookId());
            }
        }

        if(isException){
            JdbcUtils.rollbackAndClose();
        }

        if (stockOutBooks.size() == 0) {
            return null;
        }

        int[] bookId = new int[stockOutBooks.size()];

        for (int i = 0; i < bookId.length; i++) {
            bookId[i] = stockOutBooks.get(i);
        }

        return bookId;

    }

    @Override
    public int getToTalWithPrice(double min, double max) {
        String sql = "select count(*) from t_goods where price between ? and ?";
        Number number = (Number)queryForValue(sql,min,max);
        return number.intValue();

    }

    @Override
    public List<Goods> searchByKeyword(String keyword) {
        String sql="select `id`,`name`,`price`,sales`,`stock`,`img_path` imgPath from t_goods where `name` like '%?%'";
        return query(sql,keyword);
    }

    @Override
    public List<Goods> pagingQueryByPrice(int begin, int pageSize, double min, double max) {
        String sql = "select `id`,`name`,`price`,`sales`,`stock`,`img_path` as imgPath from t_goods" +
                " where price between ? and ?" +
                " limit ?,?";

        return query(sql,min,max,begin,pageSize);
    }
}
